<template>
  <div class="app-container">
    <div class="exam-container">
      <!-- 考试头部信息 -->
      <div class="exam-header">
        <div class="exam-title">
          <i class="el-icon-document"></i>
          期末考试-计算机网络
        </div>
        <div class="exam-status">
          <div class="status-item">
            <div class="status-color unanswered-color"></div>
            <span>未答</span>
          </div>
          <div class="status-item">
            <div class="status-color answered-color"></div>
            <span>已答</span>
          </div>
          <div class="status-item">
            <div class="status-color marked-color"></div>
            <span>标记</span>
          </div>
        </div>
        <div class="timer">
          <i class="el-icon-time"></i>
          倒计时：{{ formattedTime }}
        </div>
      </div>

      <!-- 考试主体 -->
      <div class="exam-body">
        <!-- 答题卡区域 -->
        <div class="answer-sheet">
          <div class="sheet-header">
            <i class="el-icon-tickets"></i>
            答题卡
          </div>

          <!-- 选择题部分 -->
          <div class="sheet-section">
            <div class="sheet-title">
              <span class="section-number">01</span>
              <span class="section-name">选择题部分</span>
              <span class="section-count">20题</span>
            </div>
            <div class="question-numbers">
              <div
                v-for="n in 20"
                :key="n"
                class="question-number"
                :class="{
                  current:
                    currentQuestionIndex === n - 1 &&
                    questions[n - 1].type === 'single',
                  answered: questions[n - 1].answered,
                  marked: questions[n - 1].marked,
                }"
                @click="goToQuestion(n - 1)"
              >
                {{ n }}
              </div>
            </div>
          </div>

          <!-- 多选题部分 -->
          <div class="sheet-section">
            <div class="sheet-title">
              <span class="section-number">02</span>
              <span class="section-name">多选题部分</span>
              <span class="section-count">14题</span>
            </div>
            <div class="question-numbers">
              <div
                v-for="n in 14"
                :key="n + 20"
                class="question-number"
                :class="{
                  current:
                    currentQuestionIndex === n + 19 &&
                    questions[n + 19].type === 'multiple',
                  answered: questions[n + 19].answered,
                  marked: questions[n + 19].marked,
                }"
                @click="goToQuestion(n + 19)"
              >
                {{ n + 20 }}
              </div>
            </div>
          </div>

          <!-- 判断题部分 -->
          <div class="sheet-section">
            <div class="sheet-title">
              <span class="section-number">03</span>
              <span class="section-name">判断题部分</span>
              <span class="section-count">9题</span>
            </div>
            <div class="question-numbers">
              <div
                v-for="n in 9"
                :key="n + 34"
                class="question-number"
                :class="{
                  current:
                    currentQuestionIndex === n + 33 &&
                    questions[n + 33].type === 'judge',
                  answered: questions[n + 33].answered,
                  marked: questions[n + 33].marked,
                }"
                @click="goToQuestion(n + 33)"
              >
                {{ n + 34 }}
              </div>
            </div>
          </div>

          <!-- 答题进度 -->
          <div class="progress-section">
            <div class="progress-title">答题进度</div>
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{ width: progressPercentage + '%' }"
              ></div>
            </div>
            <div class="progress-text">
              {{ answeredCount }}/{{ questions.length }} 题
            </div>
          </div>
        </div>

        <!-- 题目区域 -->
        <div class="question-panel">
          <div class="question-header">
            <div class="question-title">
              <span class="question-number"
                >第{{ currentQuestionIndex + 1 }}题</span
              >
              <span class="question-type">{{ questionTypeText }}</span>
            </div>
            <div class="question-meta">
              <span class="question-score"
                >分值: {{ currentQuestion.score }}分</span
              >
              <el-tag v-if="currentQuestion.marked" type="warning" size="small">
                <i class="el-icon-star-off"></i> 已标记
              </el-tag>
            </div>
          </div>

          <!-- 单选题 -->
          <div
            v-if="currentQuestion.type === 'single'"
            class="question-content-wrapper"
          >
            <div class="question-content">{{ currentQuestion.content }}</div>
            <div class="question-options">
              <div
                v-for="(option, index) in currentQuestion.options"
                :key="index"
                class="question-option"
                :class="{
                  selected: currentQuestion.userAnswer === index,
                  correct:
                    showAnswer && index === currentQuestion.correctAnswer,
                }"
                @click="selectSingleOption(index)"
              >
                <div class="option-letter">
                  {{ String.fromCharCode(65 + index) }}
                </div>
                <div class="option-text">{{ option }}</div>
                <div
                  v-if="showAnswer && index === currentQuestion.correctAnswer"
                  class="correct-indicator"
                >
                  <i class="el-icon-check"></i>
                </div>
              </div>
            </div>
          </div>

          <!-- 多选题 -->
          <div
            v-if="currentQuestion.type === 'multiple'"
            class="question-content-wrapper"
          >
            <div class="question-content">{{ currentQuestion.content }}</div>
            <div class="question-options multiple-options">
              <el-checkbox-group v-model="currentQuestion.userAnswer">
                <div
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  class="question-option"
                  :class="{
                    selected: currentQuestion.userAnswer.includes(index),
                    correct:
                      showAnswer &&
                      currentQuestion.correctAnswer.includes(index),
                  }"
                >
                  <el-checkbox :label="index" @change="selectMultipleOption">
                    <div class="option-content">
                      <div class="option-letter">
                        {{ String.fromCharCode(65 + index) }}
                      </div>
                      <div class="option-text">{{ option }}</div>
                      <div
                        v-if="
                          showAnswer &&
                          currentQuestion.correctAnswer.includes(index)
                        "
                        class="correct-indicator"
                      >
                        <i class="el-icon-check"></i>
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>

          <!-- 判断题 -->
          <div
            v-if="currentQuestion.type === 'judge'"
            class="question-content-wrapper"
          >
            <div class="question-content">{{ currentQuestion.content }}</div>
            <div class="question-options">
              <div
                class="question-option"
                :class="{
                  selected: currentQuestion.userAnswer === 0,
                  correct: showAnswer && currentQuestion.correctAnswer === 0,
                }"
                @click="selectSingleOption(0)"
              >
                <div class="option-letter">✓</div>
                <div class="option-text">正确</div>
                <div
                  v-if="showAnswer && currentQuestion.correctAnswer === 0"
                  class="correct-indicator"
                >
                  <i class="el-icon-check"></i>
                </div>
              </div>
              <div
                class="question-option"
                :class="{
                  selected: currentQuestion.userAnswer === 1,
                  correct: showAnswer && currentQuestion.correctAnswer === 1,
                }"
                @click="selectSingleOption(1)"
              >
                <div class="option-letter">✗</div>
                <div class="option-text">错误</div>
                <div
                  v-if="showAnswer && currentQuestion.correctAnswer === 1"
                  class="correct-indicator"
                >
                  <i class="el-icon-check"></i>
                </div>
              </div>
            </div>
          </div>

          <!-- 题目导航 -->
          <div class="question-nav">
            <el-button
              :disabled="currentQuestionIndex === 0"
              @click="prevQuestion"
              class="nav-button"
            >
              <i class="el-icon-arrow-left"></i>
              上一题
            </el-button>

            <div class="nav-center">
              <el-button
                type="warning"
                @click="markQuestion"
                class="mark-button"
              >
                <i
                  :class="
                    currentQuestion.marked
                      ? 'el-icon-star-on'
                      : 'el-icon-star-off'
                  "
                ></i>
                {{ currentQuestion.marked ? "取消标记" : "标记本题" }}
              </el-button>

              <!-- <el-button
                type="info"
                @click="toggleAnswer"
                class="answer-button"
              >
                <i class="el-icon-view"></i>
                {{ showAnswer ? "隐藏答案" : "显示答案" }}
              </el-button> -->
            </div>

            <el-button
              :disabled="currentQuestionIndex === questions.length - 1"
              @click="nextQuestion"
              class="nav-button"
            >
              下一题
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>

          <div class="exam-footer">
            <el-button type="danger" @click="endExam" class="end-exam-button">
              <i class="el-icon-switch-button"></i>
              结束考试
            </el-button>
            <div class="page-info">
              全卷共{{ questions.length }}题 | 总分: {{ totalScore }}分
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ExamPage",
  data() {
    return {
      currentQuestionIndex: 1, // 当前题目索引，从0开始
      timeLeft: 90 * 60, // 剩余时间（秒）
      timer: null,
      showAnswer: false, // 是否显示答案
      questions: [
        // 单选题
        {
          id: 1,
          type: "single",
          content: "在OSI参考模型中，负责路由选择的层是？",
          options: ["物理层", "数据链路层", "网络层", "传输层"],
          userAnswer: null,
          answered: false,
          marked: false,
          score: 2,
          correctAnswer: 2,
        },
        {
          id: 2,
          type: "single",
          content: "在TCP协议中采用（）来区分不同的应用进程",
          options: ["端口号", "IP地址", "MAC地址", "协议类型"],
          userAnswer: null,
          answered: false,
          marked: false,
          score: 2,
          correctAnswer: 0,
        },
        // 更多单选题...
        ...Array(18)
          .fill()
          .map((_, i) => ({
            id: i + 3,
            type: "single",
            content: `下列哪个是TCP/IP模型中的网络层协议？`,
            options: ["HTTP", "TCP", "IP", "FTP"],
            userAnswer: null,
            answered: false,
            marked: false,
            score: 2,
            correctAnswer: 2,
          })),

        // 多选题
        {
          id: 21,
          type: "multiple",
          content: "下列哪些协议属于应用层协议？（多选）",
          options: ["HTTP", "TCP", "FTP", "IP", "SMTP"],
          userAnswer: [],
          answered: false,
          marked: false,
          score: 3,
          correctAnswer: [0, 2, 4],
        },
        {
          id: 22,
          type: "multiple",
          content: "以下哪些是IPv6的特点？（多选）",
          options: [
            "地址空间更大",
            "报头格式更简单",
            "更好的安全性",
            "支持自动配置",
            "向下兼容IPv4",
          ],
          userAnswer: [],
          answered: false,
          marked: false,
          score: 3,
          correctAnswer: [0, 1, 2, 3, 4],
        },
        // 更多多选题...
        ...Array(12)
          .fill()
          .map((_, i) => ({
            id: i + 23,
            type: "multiple",
            content: `下列哪些是网络安全威胁？（多选）`,
            options: ["病毒", "木马", "DDoS攻击", "数据加密", "防火墙"],
            userAnswer: [],
            answered: false,
            marked: false,
            score: 3,
            correctAnswer: [0, 1, 2],
          })),

        // 判断题
        ...Array(9)
          .fill()
          .map((_, i) => ({
            id: i + 35,
            type: "judge",
            content: `TCP协议提供的是无连接的服务。`,
            userAnswer: null,
            answered: false,
            marked: false,
            score: 1,
            correctAnswer: 1,
          })),
      ],
    };
  },
  computed: {
    // 当前题目
    currentQuestion() {
      return this.questions[this.currentQuestionIndex];
    },
    // 格式化倒计时显示
    formattedTime() {
      const minutes = Math.floor(this.timeLeft / 60);
      const seconds = this.timeLeft % 60;
      return `${minutes.toString().padStart(2, "0")}:${seconds
        .toString()
        .padStart(2, "0")}`;
    },
    // 答题进度百分比
    progressPercentage() {
      return (this.answeredCount / this.questions.length) * 100;
    },
    // 已回答题目数量
    answeredCount() {
      return this.questions.filter((q) => q.answered).length;
    },
    // 题目类型文本
    questionTypeText() {
      const typeMap = {
        single: "单选题",
        multiple: "多选题",
        judge: "判断题",
      };
      return typeMap[this.currentQuestion.type];
    },
    // 试卷总分
    totalScore() {
      return this.questions.reduce((sum, q) => sum + q.score, 0);
    },
  },
  mounted() {
    // 开始倒计时
    this.startTimer();
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 开始倒计时
    startTimer() {
      this.timer = setInterval(() => {
        if (this.timeLeft > 0) {
          this.timeLeft--;
        } else {
          clearInterval(this.timer);
          this.$message({
            type: "warning",
            message: "考试时间已结束！",
          });
          this.endExam();
        }
      }, 1000);
    },
    // 选择单选题或判断题选项
    selectSingleOption(index) {
      this.currentQuestion.userAnswer = index;
      this.currentQuestion.answered = true;
    },
    // 选择多选题选项
    selectMultipleOption() {
      // 检查是否有选中的选项
      if (
        this.currentQuestion.userAnswer &&
        this.currentQuestion.userAnswer.length > 0
      ) {
        this.currentQuestion.answered = true;
      } else {
        this.currentQuestion.answered = false;
      }
    },
    // 标记题目
    markQuestion() {
      this.currentQuestion.marked = !this.currentQuestion.marked;
    },
    // 切换显示答案
    toggleAnswer() {
      this.showAnswer = !this.showAnswer;
    },
    // 跳转到指定题目
    goToQuestion(index) {
      this.currentQuestionIndex = index;
    },
    // 上一题
    prevQuestion() {
      if (this.currentQuestionIndex > 0) {
        this.currentQuestionIndex--;
      }
    },
    // 下一题
    nextQuestion() {
      if (this.currentQuestionIndex < this.questions.length - 1) {
        this.currentQuestionIndex++;
      }
    },
    // 结束考试
    endExam() {
      this.$confirm("确定要结束考试吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "end-exam-confirm",
      })
        .then(() => {
          clearInterval(this.timer);

          // 计算得分
          const score = this.calculateScore();

          this.$alert(`考试已结束！您的得分是：${score}分`, "考试结果", {
            confirmButtonText: "确定",
            customClass: "exam-result-alert",
            callback: () => {
              // 可以在这里添加提交成绩或跳转页面的逻辑
            },
          });
        })
        .catch(() => {
          // 取消操作
        });
    },
    // 计算得分
    calculateScore() {
      let score = 0;

      this.questions.forEach((question) => {
        if (question.answered) {
          if (question.type === "single" || question.type === "judge") {
            if (question.userAnswer === question.correctAnswer) {
              score += question.score;
            }
          } else if (question.type === "multiple") {
            // 多选题需要完全正确才得分
            const userAnswers = [...question.userAnswer].sort();
            const correctAnswers = [...question.correctAnswer].sort();
            if (
              userAnswers.length === correctAnswers.length &&
              userAnswers.every(
                (value, index) => value === correctAnswers[index]
              )
            ) {
              score += question.score;
            }
          }
        }
      });

      return score;
    },
  },
};
</script>

<style lang="scss" scoped>
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$bg-color: #f5f7fa;
$card-bg: #ffffff;
$border-color: #e4e7ed;
$shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

.exam-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
  background-color: $bg-color;
  min-height: 100vh;
}

.exam-header {
  background: linear-gradient(135deg, $primary-color, #66b1ff);
  border-radius: 12px;
  padding: 18px 25px;
  box-shadow: $shadow;
  margin-bottom: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.exam-title {
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;

  i {
    margin-right: 8px;
    font-size: 22px;
  }
}

.exam-status {
  display: flex;
  gap: 25px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.status-color {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.unanswered-color {
  background-color: $danger-color;
}

.answered-color {
  background-color: $success-color;
}

.marked-color {
  background-color: $warning-color;
}

.timer {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;

  i {
    margin-right: 8px;
    font-size: 18px;
  }
}

.exam-body {
  display: flex;
  gap: 25px;
}

.question-panel {
  flex: 1;
  background-color: $card-bg;
  border-radius: 12px;
  padding: 25px;
  box-shadow: $shadow;
  display: flex;
  flex-direction: column;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid $border-color;
}

.question-title {
  display: flex;
  align-items: center;
  gap: 15px;
}

.question-number {
  font-size: 18px;
  font-weight: bold;
  color: $primary-color;
}

.question-type {
  background-color: lighten($primary-color, 40%);
  color: $primary-color;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
}

.question-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.question-score {
  font-size: 14px;
  color: $info-color;
}

.question-content-wrapper {
  flex: 1;
}

.question-content {
  font-size: 16px;
  line-height: 1.7;
  margin-bottom: 30px;
  padding: 15px;
  background-color: lighten($bg-color, 2%);
  border-radius: 8px;
  border-left: 4px solid $primary-color;
}

.question-options {
  margin-bottom: 30px;
}

.question-option {
  margin-bottom: 15px;
  padding: 15px 20px;
  border: 1px solid $border-color;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  position: relative;

  &:hover {
    border-color: $primary-color;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }

  &.selected {
    border-color: $primary-color;
    background-color: lighten($primary-color, 42%);
  }

  &.correct {
    border-color: $success-color;
    background-color: lighten($success-color, 45%);
  }
}

.option-letter {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  border-radius: 50%;
  margin-right: 15px;
  font-weight: bold;
  color: $info-color;
  border: 1px solid $border-color;
  transition: all 0.3s;
}

.question-option.selected .option-letter,
.question-option.correct .option-letter {
  background-color: $primary-color;
  color: white;
  border-color: $primary-color;
}

.question-option.correct .option-letter {
  background-color: $success-color;
  border-color: $success-color;
}

.option-text {
  flex: 1;
}

.correct-indicator {
  color: $success-color;
  font-weight: bold;
  display: flex;
  align-items: center;

  i {
    margin-left: 5px;
  }
}

// 多选题样式
.multiple-options {
  .question-option {
    display: flex;
    align-items: center;

    ::v-deep .el-checkbox {
      width: 100%;
      display: flex;
      align-items: center;
    }

    ::v-deep .el-checkbox__input {
      margin-right: 15px;
    }
  }
}

.option-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.question-nav {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.nav-button {
  padding: 12px 25px;
  border-radius: 8px;
  font-weight: bold;

  i {
    margin: 0 5px;
  }
}

.nav-center {
  display: flex;
  gap: 15px;
}

.mark-button,
.answer-button {
  padding: 12px 20px;
  border-radius: 8px;
  font-weight: bold;

  i {
    margin-right: 5px;
  }
}

.exam-footer {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid $border-color;
}

.end-exam-button {
  padding: 12px 30px;
  border-radius: 8px;
  font-weight: bold;

  i {
    margin-right: 5px;
  }
}

.page-info {
  margin-top: 15px;
  color: $info-color;
  font-size: 14px;
}

.answer-sheet {
  width: 320px;
  background-color: $card-bg;
  border-radius: 12px;
  padding: 0;
  box-shadow: $shadow;
  height: fit-content;
}

.sheet-header {
  background: linear-gradient(135deg, $primary-color, #66b1ff);
  color: white;
  padding: 18px 25px;
  border-radius: 12px 12px 0 0;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;

  i {
    margin-right: 10px;
    font-size: 20px;
  }
}

.sheet-section {
  padding: 20px 25px;
  border-bottom: 1px solid $border-color;

  &:last-of-type {
    border-bottom: none;
  }
}

.sheet-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.section-number {
  background-color: $primary-color;
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}

.section-name {
  flex: 1;
  margin-left: 10px;
  font-weight: bold;
}

.section-count {
  color: $info-color;
  font-size: 13px;
}

.question-numbers {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.question-number {
  width: 38px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid $border-color;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;

  &:hover {
    border-color: $primary-color;
    color: $primary-color;
    transform: translateY(-2px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }

  &.current {
    border-color: $primary-color;
    background: linear-gradient(135deg, $primary-color, #66b1ff);
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
  }

  &.answered {
    border-color: $success-color;
    background-color: $success-color;
    color: white;
  }

  &.marked {
    border-color: $warning-color;
    background-color: $warning-color;
    color: white;
  }
}

.progress-section {
  padding: 20px 25px;
  background-color: lighten($bg-color, 2%);
  border-radius: 0 0 12px 12px;
}

.progress-title {
  font-weight: bold;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.progress-bar {
  height: 8px;
  background-color: lighten($border-color, 5%);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(
    90deg,
    $success-color,
    lighten($success-color, 10%)
  );
  border-radius: 4px;
  transition: width 0.5s ease;
}

.progress-text {
  text-align: center;
  font-size: 14px;
  color: $info-color;
}

// 响应式设计
@media (max-width: 1200px) {
  .exam-body {
    flex-direction: column;
  }

  .answer-sheet {
    width: 100%;
    margin-bottom: 20px;
  }

  .question-numbers {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .exam-container {
    padding: 10px;
  }

  .exam-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .question-nav {
    flex-direction: column;
    gap: 15px;
  }

  .nav-center {
    order: -1;
    justify-content: center;
  }
}
</style>

<style>
/* 全局样式调整 */
.end-exam-confirm .el-message-box__status {
  font-size: 24px !important;
}

.exam-result-alert .el-message-box__content {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.exam-result-alert .el-message-box__status {
  font-size: 28px !important;
  color: #409eff;
}
</style>
